package com.lanhai.webservice.netty;

import io.netty.channel.*;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service("NettyServer")
public class NettyServer {

    /**
     * boss 线程组用于处理连接工作
     */
    private EventLoopGroup boss;

    @Autowired
    private NettyServeHandler nettyServeHandler;

    @Value("${netty.port:5500}")
    private Integer port;

    /**
     * SpringBoot 启动的时候 调用
     *
     * @throws InterruptedException
     */
    public void init() throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        //优化使用的线程
        final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
        boss = new NioEventLoopGroup();
        try {
            bootstrap.group(boss)
                    .channel(NioDatagramChannel.class)
                    .handler(nettyServeHandler);
            ChannelFuture cf = bootstrap.bind(port).sync();

            //给cf注册监听器 监控关心的事件
            cf.addListener((GenericFutureListener<? extends Future<? super Void>>) (future) -> {
                if (cf.isSuccess()) {
                    System.out.println("监听端口" + port + "成功");

                }
            });

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } finally {
            if (boss != null) {
                boss.shutdownGracefully().sync();
                System.out.println("关闭监听端口" + port + "成功");
            }
        }
    }


    public void shutdown() throws InterruptedException {
        if (boss != null) {
            boss.shutdownGracefully().sync();
            System.out.println("关闭监听端口" + port + "成功");
        }
    }
}
